package com.opengl.camera;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.SurfaceHolder;
import android.hardware.Camera;

class CameraGLSurfaceView extends GLSurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
	
	private CameraRenderer m_cameraRenderer;
	private byte[] m_glCameraFrame;
	private Context m_context;
	
	public CameraGLSurfaceView(Context context){
		super(context);

		m_context = context;
		initRenderer();
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
	}

	private void initRenderer()
	{
		// Create an OpenGL ES 2.0 context
		setEGLContextClientVersion(2);

		// Set the Renderer for drawing on the GLSurfaceView
		m_cameraRenderer = new CameraRenderer(m_context);
		setRenderer(m_cameraRenderer);

		// Render the view only when there is a change in the drawing data
		setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
	}
	
	private boolean updateCameraTexture()
	{
		queueEvent(new Runnable()
		{
			@Override
			public void run()
			{
				m_cameraRenderer.updateTexture(m_glCameraFrame);
			}
		});
		return true;
	}
	
	@Override
	public void onPreviewFrame(byte[] data, Camera camera) 
	{
		int texSize = CameraParams.textureSize;
		int cols = CameraParams.cameraSize.x;
		int rows = CameraParams.cameraSize.y;
		
		 //allocate byte array to the size of a texture with power of 2
		if (m_glCameraFrame==null) m_glCameraFrame=new byte[texSize*texSize];
		
		// convert the camera data from YUV to grayscale.
		// this is done by just grabbing the first row*cols worth of data in YUV format
   		int bwCounter=0;
   		int yuvsCounter=0;
   		for (int y=0;y<rows;y++) {
   			System.arraycopy(data, yuvsCounter, m_glCameraFrame, bwCounter, cols);
   			yuvsCounter=yuvsCounter+cols;
   			bwCounter=bwCounter+texSize;
   		}
   		
   		// send the texture to the renderer with the runnable queueEvent
   		if(updateCameraTexture())
   		{
   			// request a render since we have sent a new texture!
   			this.requestRender();
   		}
	}
}